//
//  AppDelegate.m
//  TaoTuo
//
//  Created by admin on 2019/8/15.
//  Copyright © 2019 admin. All rights reserved.
//

#import "AppDelegate.h"
#import "AppDelegate+Setup.h"
#import "LLTabbarViewController.h"
#import "OttoFPSButton.h"
#import <AlipaySDK/AlipaySDK.h>
#import "TTGuideViewController.h"

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    //uuid
    if ([LLPasswordManagerUtilies getUUIDString].length == 0) {
        NSString *uuidStr = [NSUUID UUID].UUIDString;
        [LLPasswordManagerUtilies saveUUIDString:uuidStr];
    }
    
    
    [self setupNav];
    [self setupKeyboard];
    [self setToastManager];
    [self setupUM];
    
    //向微信注册
    [WXApi registerApp:WeiXinAPPID universalLink:@"https://alipay.idecd.cn/taotuo/"];
    
    [self setupRootViewController];
    
    [self requestAgentInfo];
    
//#ifdef DEBUG
//    CGRect frame = CGRectMake(0, 300, 80, 30);
//    UIColor *btnBGColor = [UIColor colorWithWhite:0.000 alpha:0.700];
//    OttoFPSButton *btn = [OttoFPSButton setTouchWithFrame:frame titleFont:[UIFont systemFontOfSize:15] backgroundColor:btnBGColor backgroundImage:nil];
//    [self.window addSubview:btn];
//#endif
    
    return YES;
}


- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
    UIView *view = [UIApplication sharedApplication].keyWindow;
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            if ([resultDic[@"resultStatus"] intValue] == 9000) {
                // 支付成功
                [[NSNotificationCenter defaultCenter] postNotificationName:[TTLoginSingle sharedSingle].alipaySuccessNotifyKey object:nil];
            } else {
                NSString *string = [NSString stringWithFormat:@"%@ 支付失败", resultDic[@"resultStatus"]];
                [view makeToast:string];
            }
        }];
    } else {
        NSLog(@">>> %@", url);
        return [WXApi handleOpenURL:url delegate:self];
    }
    return YES;
}

- (void)setupRootViewController
{
    // 取出上次保存的版本号
    NSString *lastVersion = [USER_DEFAULT objectForKey:lastVersionKey];
    // 当前版本号
    NSString *currentVersion = kCurrentVersion;
    
    if ([lastVersion isEqualToString:currentVersion]) {
        // 如果上次的版本号等于当前版本号，则不显示引导页
        LLTabbarViewController *tabbarVC = [[LLTabbarViewController alloc] init];
        self.window.rootViewController = tabbarVC;
        if (@available(iOS 13.0, *)) {
            // 不使用暗黑模式
            [tabbarVC setOverrideUserInterfaceStyle:UIUserInterfaceStyleLight];
        }
        
    } else {
        [USER_DEFAULT setObject:currentVersion forKey:lastVersionKey];
        [USER_DEFAULT synchronize];
        
        TTGuideViewController *guideVC = [[TTGuideViewController alloc] init];
        self.window.rootViewController = guideVC;
    }
}

///控制屏幕旋转
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    // 可旋转至 上 左 右
    return self.allowRotate ? (UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight) : UIInterfaceOrientationMaskPortrait;
}



///点击通用链接跳转过来的
- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler
{
//    NSLog(@"点击通用链接跳转过来的 >>> %@", userActivity.webpageURL.absoluteString);
    return [WXApi handleOpenUniversalLink:userActivity delegate:self];
    
}

//- (void)onResp:(BaseResp *)resp
//{
////    NSLog(@">>> %d,,, %@", resp.errCode, resp.errStr);
//    if (resp.errCode == WXSuccess) {
//        [[UIApplication sharedApplication].keyWindow makeToast:@"分享成功"];
//    }
//}

/// 请求业务员信息，把登录信息里面对应的字段替换掉
- (void)requestAgentInfo
{
    NSString *account = [TTLoginSingle sharedSingle].loginModel.Account;
    if (account.length == 0) {
        return;
    }
    NSDictionary *dic = @{
        @"param.account" : account
    };
    [[LLNetworkManagerTool sharedManager] requestMethod:GET urlString:getRelationSalesmanInfo_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        TTLoginModel *model = [TTLoginSingle sharedSingle].loginModel;
        model.SalesmanAccountId = [NSString stringWithFormat:@"%@", responseObject[@"SalesmanAccountId"]];
        model.SalesmanAccountName = responseObject[@"SalesmanAccountName"];
        model.SalesmanPicture = responseObject[@"SalesmanPicture"];
        model.SalesmanMobile = responseObject[@"SalesmanMobile"]; 
        model.ChatInfoId = [NSString stringWithFormat:@"%@", responseObject[@"ChatInfoId"]];
        model.TranslateId = [NSString stringWithFormat:@"%@", responseObject[@"TranslateId"]];
        model.PlantFrom = [NSString stringWithFormat:@"%@", responseObject[@"PlantFrom"]];
        model.ChatType = [NSString stringWithFormat:@"%@", responseObject[@"ChatType"]];
        model.ChatName = [NSString stringWithFormat:@"%@", responseObject[@"ChatName"]];
        model.ChatMark = [NSString stringWithFormat:@"%@", responseObject[@"ChatMark"]];
        
        // 保存
        [TTLoginSingle setupUserDataWithModel:model];
        
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
    } showLoadingInView:nil];
    
}











- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
